package com.truckdispatching.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.truckdispatching.R;
import com.truckdispatching.UserManager;
import com.truckdispatching.http.controller.RegisterHttpController;
import com.truckdispatching.http.util.OnResponseHandler;

/**
 * 注册界面
 * 
 * @author Lee
 * @date 2013-4-30
 */
public class RegisterAcivity extends BaseActivity implements OnClickListener {

	private EditText mName;
	private EditText mMobile;
	private EditText mCarNumber;
	private TextView mCarLength;
	private TextView mPlace1;
	private TextView mPlace2;
	private TextView mPlace3;

	private CheckBox mReadCheck;

	private Button mBtnBack;
	private Button mBtnRegister;
	private TextView mBtnXieyi;

	private RegisterHttpController mRegisterHttpController;

	private String mImei = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_activity);

		mImei = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();

		mName = (EditText) findViewById(R.id.register_name);
		mMobile = (EditText) findViewById(R.id.register_mobile);
		mCarNumber = (EditText) findViewById(R.id.register_carnumber);
		mCarNumber.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() == 7) {
					InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					im.hideSoftInputFromWindow(mCarNumber.getWindowToken(), 0);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		mCarLength = (TextView) findViewById(R.id.register_carlength);
		mCarLength.setOnClickListener(this);
		mPlace1 = (TextView) findViewById(R.id.register_place1);
		mPlace1.setOnClickListener(this);
		mPlace2 = (TextView) findViewById(R.id.register_place2);
		mPlace2.setOnClickListener(this);
		mPlace3 = (TextView) findViewById(R.id.register_place3);
		mPlace3.setOnClickListener(this);

		mBtnBack = (Button) findViewById(R.id.btn_back);
		mBtnBack.setOnClickListener(this);
		mBtnRegister = (Button) findViewById(R.id.btn_register);
		mBtnRegister.setOnClickListener(this);

		mBtnXieyi = (TextView) findViewById(R.id.btn_xieyi);
		mBtnXieyi.setOnClickListener(this);

		mReadCheck = (CheckBox) findViewById(R.id.read);
		mReadCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mBtnRegister.setEnabled(isChecked);
			}
		});

	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, LoginActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.register_carlength: {
			Intent intent = new Intent(RegisterAcivity.this, ChoseCarLengthActivity.class);
			startActivityForResult(intent, 1);
			break;
		}
		case R.id.register_place1: {
			Intent intent = new Intent(RegisterAcivity.this, ChoseProvinceActivity.class);
			startActivityForResult(intent, 2);
			break;
		}
		case R.id.register_place2: {
			Intent intent = new Intent(RegisterAcivity.this, ChoseProvinceActivity.class);
			startActivityForResult(intent, 3);
			break;
		}
		case R.id.register_place3: {
			Intent intent = new Intent(RegisterAcivity.this, ChoseProvinceActivity.class);
			startActivityForResult(intent, 4);
			break;
		}
		case R.id.btn_back:
			onBackPressed();
			break;
		case R.id.btn_register: {
			final String name = mName.getText().toString().trim();
			if (!checkName(name)) {
				break;
			}
			final String phoneNumber = mMobile.getText().toString().trim();
			if (!checkPhoneNumber(phoneNumber)) {
				break;
			}
			final String carNumber = mCarNumber.getText().toString().trim();
			if (!checkCarNumber(carNumber)) {
				break;
			}
			final String carLength = mCarLength.getText().toString().trim();
			if (!checkCarLength(carLength)) {
				break;
			}
			// 发送注册网络请求
			if (mRegisterHttpController != null) {
				mRegisterHttpController.cancelHttpRequest();
				mRegisterHttpController = null;
			}
			final String target1 = mPlace1.getText().toString().trim();
			final String target2 = mPlace2.getText().toString().trim();
			final String target3 = mPlace3.getText().toString().trim();
			mRegisterHttpController = new RegisterHttpController();
			mRegisterHttpController.setOnResponseListener(new OnResponseHandler() {

				@Override
				public void onResponse(Object response) {
					dismissLoadingDialog();
					showToast("注册成功");
					UserManager.setName(name);
					UserManager.setMobile(phoneNumber);
					UserManager.setTruckNumber(carNumber);
					UserManager.setTruckLength(carLength);
					UserManager.setTarget1(target1);
					UserManager.setTarget2(target2);
					UserManager.setTarget3(target3);

					Intent intent = new Intent(RegisterAcivity.this, RegisterCompleteActivity.class);
					intent.putExtra("mobile", phoneNumber);
					startActivity(intent);
					finish();
				}

				@Override
				public void onResponseError(int errorCode, String errorMessage) {
					dismissLoadingDialog();
					if (errorMessage != null && !errorMessage.equals("")) {
						showToast("注册失败：" + errorMessage);
					} else {
						showToast("注册失败");
					}
				}
			});
			mRegisterHttpController.sendRequest(name, phoneNumber, carNumber, carLength, target1, target2, target3, mImei);
			showLoadingDialog();
			break;
		}
		case R.id.btn_xieyi: {
			Intent intent = new Intent(RegisterAcivity.this, AgreementActivity.class);
			startActivity(intent);
			break;
		}
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 100) {
			switch (requestCode) {
			case 1:
				String carLength = data.getExtras().getString("result");
				mCarLength.setText(carLength);
				break;
			case 2:
				String place1 = data.getExtras().getString("result");
				if (place1.contains("不限")) {
					place1 = place1.split(" ")[0];
				}
				mPlace1.setText(place1);
				break;
			case 3:
				String place2 = data.getExtras().getString("result");
				if (place2.contains("不限")) {
					place2 = place2.split(" ")[0];
				}
				mPlace2.setText(place2);
				break;
			case 4:
				String place3 = data.getExtras().getString("result");
				if (place3.contains("不限")) {
					place3 = place3.split(" ")[0];
				}
				mPlace3.setText(place3);
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean checkName(String name) {
		if (name.equals("")) {
			showToast("请输入姓名");
			mName.requestFocus();
			return false;
		}
		if(!name.matches("([\u4e00-\u9fa5]){1,10}")){
			showToast("请输入汉字");
			mName.requestFocus();
			return false;
		}
		return true;
	}

	private boolean checkPhoneNumber(String phonenumber) {
		if (phonenumber.equals("")) {
			showToast("请输入手机号");
			mMobile.requestFocus();
			return false;
		}
		if (phonenumber.length() != 11) {
			showToast("手机号格式错误");
			mMobile.requestFocus();
			return false;
		}
		if (!phonenumber.startsWith("1")) {
			showToast("手机号格式错误");
			mMobile.requestFocus();
			return false;
		}
		return true;
	}

	private boolean checkCarNumber(String carnumber) {
		if (carnumber.equals("")) {
			showToast("请输入车牌号");
			mCarNumber.requestFocus();
			return false;
		}
		if (carnumber.length() != 7) {
			showToast("车牌号格式错误");
			mCarNumber.requestFocus();
			return false;
		}
		return true;
	}

	private boolean checkCarLength(String length) {
		if (length.equals("")) {
			showToast("请选择车长");
			return false;
		}
		return true;
	}
}
